package com.koron.car.web.driver.service.impl;

import com.alibaba.fastjson.JSON;
import com.koron.bean.system.staff.vo.EamUser;
import com.koron.bean.workflow.RedirectQuery;
import com.koron.car.config.Constants;
import com.koron.car.web.common.CommonUtils;
import com.koron.car.web.driver.bean.query.DriverQuery;
import com.koron.car.web.driver.bean.vo.DriverVO;
import com.koron.car.web.driver.mapper.DriverMapper;
import com.koron.car.web.driver.service.DriverService;
import com.koron.common.core.config.ThreadLocalContext;
import com.koron.common.core.util.CodeTools;
import com.koron.common.core.util.OrgCacheUtils;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.koron.ebs.mybatis.TaskAnnotation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
public class DriverServiceImpl implements DriverService {

    @Autowired
    private ApplicationContext ctx;

    @Autowired
    private OrgCacheUtils orgCacheUtils;

    /**
     * 通过ID查询单条数据
     * @param factory
     * @param id      主键
     * @return 实例对象
     */
    @Override
    @TaskAnnotation("queryById")
    public DriverVO queryById(SessionFactory factory, String id) {
        DriverMapper mapper = factory.getMapper(DriverMapper.class);
        DriverVO driverVO = mapper.queryById(id);
        driverVO.setApplyDeptName(orgCacheUtils.getOrgNameById(driverVO.getApplyDeptId()));
        return driverVO;
    }

    /**
     * 查询多条数据
     * @param factory
     * @param query  查询条件
     * @return 对象列表
     */
    @Override
    @TaskAnnotation("queryList")
    public List<DriverVO> queryList(SessionFactory factory, DriverQuery query) {
        DriverMapper mapper = factory.getMapper(DriverMapper.class);
        List<DriverVO> driverVOS = mapper.queryList(query);
        driverVOS.stream().forEach(row -> row.setApplyDeptName(orgCacheUtils.getOrgNameById(row.getApplyDeptId())));
        return driverVOS;
    }

    @Override
    @TaskAnnotation("schedulable")
    public List<DriverVO> schedulable(SessionFactory factory, DriverQuery query) {
        DriverMapper mapper = factory.getMapper(DriverMapper.class);
        query.setDeleteFlag(false);
        List<DriverVO> driverVOS = mapper.queryList(query);
        return driverVOS;
    }

    /**
     * 修改数据
     *
     * @param factory
     * @param driver 实例对象
     * @return 实例对象
     */
    @Override
    @TaskAnnotation("saveOrUpdate")
    public DriverVO saveOrUpdate(SessionFactory factory, DriverVO driver) {
        DriverMapper mapper = factory.getMapper(DriverMapper.class);
        if(StringUtils.isBlank(driver.getId())) {
            // 同一个账号的司机，不能添加多次
            String account = driver.getAccount();
            Assert.hasText(account, "司机账号不能为空");
            DriverVO oldDriver = mapper.queryByAccount(account);
            if (Objects.nonNull(oldDriver) && !oldDriver.getDeleteFlag()) {
                Assert.isNull(oldDriver, "司机[" + account + "]已存在");
                // 初始化为空闲状态
                driver.setId(oldDriver.getId());
            }
            driver.setDeleteFlag(false);
            driver.setWorkState(Constants.DriverWorkState.FREE);
        }else {
            DriverVO driverVO = mapper.queryById(driver.getId());
            if (Objects.nonNull(driverVO)){
                driver.setWorkState(driverVO.getWorkState());
            }
        }
        // 发布事件
        //ctx.publishEvent(new MotorcadeEvent(driver.getMotorcadeName(), this));
        CommonUtils.update(driver, ThreadLocalContext.get());
        CommonUtils.update(driver);
        if(StringUtils.isBlank(driver.getId())){
            driver.setApplyState(Constants.PartTimeState.DRAFT );
        }
        driver.setId(StringUtils.isBlank(driver.getId()) ? CodeTools.getCode32() : driver.getId());
        EamUser eamUser = ThreadLocalContext.get();
        driver.setDeptId(StringUtils.isBlank(driver.getDeptId()) ? eamUser.getOrgId() : driver.getDeptId());
        // 清空申请信息id，防止前端传入
        driver.setApplyId(null);
        if(StringUtils.equals(Constants.DriverType.PART_TIME, driver.getDriverType())) {
            driver.setApplyId(StringUtils.isBlank(driver.getApplyId()) ? CodeTools.getCode32() : driver.getApplyId());
        }
        if(driver.getSubmit()) {
            driver.setWorkState(Constants.DriverWorkState.FREE);
        }
        mapper.saveOrUpdate(driver);
        return driver;
    }

    /**
     * 通过主键删除数据
     *
     * @param factory
     * @param id      主键
     * @return 是否成功
     */
    @Override
    @TaskAnnotation("deleteById")
    public boolean deleteById(SessionFactory factory, String id) {
        DriverMapper mapper = factory.getMapper(DriverMapper.class);
        return mapper.deleteById(id) > 0;
    }


    /**
     * 通过主键逻辑删除数据
     *
     * @param factory
     * @param id      主键
     * @return 是否成功
     */
    @Override
    @TaskAnnotation("hiddenById")
    public boolean hiddenById(SessionFactory factory, String id) {
        DriverMapper mapper = factory.getMapper(DriverMapper.class);
        return mapper.hiddenById(id) > 0;
    }

    @Override
    @TaskAnnotation("getDriverByPhone")
    public DriverVO getDriverByPhone(SessionFactory factory, String phone) {
        DriverMapper mapper = factory.getMapper(DriverMapper.class);
        DriverVO driverVO = mapper.getDriverByPhone(phone);
        return driverVO;
    }


    /**
     * 由业务扭转导致状态变化
     * @param factory
     * @param driverId
     * @param state
     * @return
     */
    @Override
    @TaskAnnotation("updateWorkState")
    public synchronized Boolean updateWorkState(SessionFactory factory, String driverId, String state) {
        DriverMapper mapper = factory.getMapper(DriverMapper.class);
        return mapper.updateWorkStatusById(driverId, state) > 0;
    }



    /**
     * 工作流更新
     *
     * @param factory
     * @param redirectQuery
     */
    @Override
    @TaskAnnotation("workflowUpdate")
    public Boolean workflowUpdate(SessionFactory factory, RedirectQuery redirectQuery) {
        Integer operation = redirectQuery.getOperation();
        DriverVO vo = JSON.parseObject(redirectQuery.getFormVariables(), DriverVO.class);
        DriverMapper mapper = factory.getMapper(DriverMapper.class);
        switch (operation) {
            case 256: // 撤回
            case 1: // 驳回
                // 驳回的节点编号
                vo.setApplyState(Constants.PartTimeState.DRAFT);
                break;
            case 32: // 同意
                vo.setApplyState(Constants.PartTimeState.WAIT_APPROVE);
                break;
        }
        // 更新状态
        mapper.updateApplyStatusById(vo.getId(), vo.getApplyState(), vo.getCurrNodeUser(), new Date());
        return true;
    }

    /**
     * 审核完成
     *
     * @param factory
     * @param detail
     * @return
     */
    @Override
    @TaskAnnotation("auditFinish")
    public DriverVO auditFinish(SessionFactory factory, DriverVO detail) {
        DriverMapper mapper = factory.getMapper(DriverMapper.class);
        detail.setApplyState(Constants.PartTimeState.FINISH);
        detail.setWorkState(Constants.DriverWorkState.FREE);
        mapper.updateApplyStatusById(detail.getId(), detail.getApplyState(), detail.getCurrNodeUser(), new Date());
        mapper.updateWorkStatusById(detail.getId(), detail.getWorkState());
        return detail;
    }

    /**
     * 更新状态
     * @param factory
     * @param driverId
     * @param state
     * @return
     */
    @Override
    @TaskAnnotation("updateState")
    public synchronized boolean updateState(SessionFactory factory, String driverId, String state) {
        DriverMapper mapper = factory.getMapper(DriverMapper.class);
        return mapper.updateWorkStatusById(driverId, state) > 0;
    }
}
